<template>
  <div class="supplier-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">供应商管理</span>
          <div class="right-button">
            <el-button type="primary" :icon="useRenderIcon(AddFill)" @click="handleAdd">
              新增供应商
            </el-button>
            <el-button type="info" :icon="useRenderIcon(Upload)" @click="handleImport">
              导入
            </el-button>
            <el-button type="warning" :icon="useRenderIcon(Download)" @click="handleExport">
              导出
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item label="供应商名称" prop="supplierName">
          <el-input
            v-model="queryParams.supplierName"
            placeholder="请输入供应商名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="供应商编码" prop="supplierCode">
          <el-input
            v-model="queryParams.supplierCode"
            placeholder="请输入供应商编码"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="合作状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="合作状态"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="useRenderIcon(Search)" @click="handleQuery"
            >搜索</el-button
          >
          <el-button :icon="useRenderIcon(Refresh)" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="supplierList" style="width: 100%" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="supplierId" label="供应商编号" align="center" width="100" />
        <el-table-column
          prop="supplierName"
          label="供应商名称"
          align="center"
          min-width="150"
          :show-overflow-tooltip="true"
        />
        <el-table-column prop="supplierCode" label="供应商编码" align="center" width="120" />
        <el-table-column prop="contactName" label="联系人" align="center" width="120" />
        <el-table-column prop="contactPhone" label="联系电话" align="center" width="150" />
        <el-table-column
          prop="contactEmail"
          label="电子邮箱"
          align="center"
          width="180"
          :show-overflow-tooltip="true"
        />
        <el-table-column prop="status" label="合作状态" align="center" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
              {{ scope.row.status === "0" ? "合作中" : "已终止" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              :icon="useRenderIcon(EditPen)"
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              :icon="useRenderIcon(View)"
              @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-popconfirm
              :title="`是否确认删除供应商'${scope.row.supplierName}'?`"
              @confirm="handleDelete(scope.row)"
            >
              <template #reference>
                <el-button link type="danger" size="small" :icon="useRenderIcon(Delete)"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
        <template #empty>
          <div class="empty-block">
            <el-empty description="暂无供应商数据" />
            <div class="empty-tips">
              您可以点击"新增供应商"按钮添加供应商信息或者联系管理员导入供应商数据
            </div>
          </div>
        </template>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        :currentPage="queryParams.pageNum"
        :pageSize="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </el-card>

    <!-- 供应商表单组件 -->
    <SupplierForm
      v-if="dialog.visible"
      v-model="dialog.visible"
      :title="dialog.title"
      :supplier="form"
      @success="getList"
    />

    <!-- 供应商详情组件 -->
    <SupplierDetail v-if="detailVisible" v-model="detailVisible" :supplier="currentSupplier" />

    <!-- 导入对话框 -->
    <el-dialog title="导入供应商数据" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            <el-button type="primary" link @click="handleDownloadTemplate">下载模板</el-button>
            <span>仅允许导入xls、xlsx格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="upload.open = false">取 消</el-button>
          <el-button type="primary" @click="submitFileForm" :loading="upload.isUploading"
            >确 定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, FormInstance, UploadInstance } from "element-plus";
import {
  getSupplierList,
  deleteSupplier,
  exportSupplier,
  downloadImportTemplate
} from "@/api/attendance/supplier";
import { SupplierVO, SupplierQuery } from "@/types/attendance/supplier/index";
import { UploadFilled } from "@element-plus/icons-vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import AddFill from "@iconify-icons/ri/add-circle-line";
import Upload from "@iconify-icons/ep/upload";
import Download from "@iconify-icons/ep/download";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import View from "@iconify-icons/ep/document";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";

// 导入自定义组件
import SupplierForm from "./components/SupplierForm.vue";
import SupplierDetail from "./components/SupplierDetail.vue";

// 状态选项
const statusOptions = [
  { value: "0", label: "合作中" },
  { value: "1", label: "已终止" }
];

// 查询参数
const queryParams = reactive<SupplierQuery>({
  supplierName: "",
  supplierCode: "",
  status: "",
  pageNum: 1,
  pageSize: 10
});

// 表格数据
const supplierList = ref<SupplierVO[]>([]);
const loading = ref(false);
const total = ref(0);

// 供应商详情
const detailVisible = ref(false);
const currentSupplier = ref<SupplierVO>({} as SupplierVO);

// 对话框属性
const dialog = reactive({
  title: "",
  visible: false
});

// 表单数据
const form = reactive<SupplierVO>({
  supplierName: "",
  supplierCode: "",
  contactName: "",
  contactPhone: "",
  contactEmail: "",
  address: "",
  status: "0",
  remark: ""
});

// 上传相关
const upload = reactive({
  open: false,
  url: "/attendance/supplier/import",
  headers: { Authorization: "Bearer " + localStorage.getItem("token") },
  isUploading: false
});

// 表单引用
const queryRef = ref<FormInstance>();
const uploadRef = ref<UploadInstance>();

// 获取供应商列表
const getList = async () => {
  loading.value = true;
  try {
    console.log("查询参数:", queryParams);
    const res = await getSupplierList(queryParams);
    console.log("查询结果:", res);
    supplierList.value = res.data.rows || [];
    total.value = res.data.total || 0;
  } catch (error) {
    console.error("获取供应商列表失败", error);
    ElMessage.error("获取供应商列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  // 完全重置查询参数为初始值
  queryParams.supplierName = "";
  queryParams.supplierCode = "";
  queryParams.contactName = "";
  queryParams.status = "";
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;

  // 如果存在表单引用，也重置表单
  if (queryRef.value) {
    queryRef.value.resetFields();
  }

  console.log("重置后的查询参数:", queryParams);
  getList();
};

// 分页操作
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size;
  getList();
};

// 页码操作
const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page;
  getList();
};

// 新增按钮操作
const handleAdd = () => {
  dialog.title = "添加供应商";
  dialog.visible = true;
  resetForm();
};

// 编辑按钮操作
const handleUpdate = (row: SupplierVO) => {
  dialog.title = "修改供应商";
  dialog.visible = true;
  resetForm();
  Object.assign(form, row);
};

// 查看按钮操作
const handleView = (row: SupplierVO) => {
  currentSupplier.value = row;
  detailVisible.value = true;
};

// 删除按钮操作
const handleDelete = async (row: SupplierVO) => {
  try {
    // 确保 supplierId 是有效的
    if (!row.supplierId) {
      ElMessage.error("供应商ID无效");
      return;
    }

    console.log("删除操作，供应商ID:", row.supplierId);

    // 转换为数组格式并显式转为数字类型
    const idArray = [Number(row.supplierId)];
    console.log("删除操作，ID数组:", idArray);

    // 发起删除请求
    await deleteSupplier(idArray);
    ElMessage.success("删除成功");
    getList(); // 刷新列表
  } catch (error) {
    console.error("删除失败", error);
    ElMessage.error("删除失败");
  }
};

// 导出按钮操作
const handleExport = () => {
  exportSupplier(queryParams);
};

// 导入按钮操作
const handleImport = () => {
  upload.open = true;
};

// 下载导入模板
const handleDownloadTemplate = () => {
  downloadImportTemplate();
};

// 文件上传中
const handleFileUploadProgress = () => {
  upload.isUploading = true;
};

// 文件上传成功
const handleFileSuccess = (response: any) => {
  upload.open = false;
  upload.isUploading = false;
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }

  ElMessage.success(response.msg || "导入成功");
  getList();
};

// 提交上传文件
const submitFileForm = () => {
  if (uploadRef.value) {
    uploadRef.value.submit();
  }
};

// 重置表单
const resetForm = () => {
  form.supplierId = undefined;
  form.supplierName = "";
  form.supplierCode = "";
  form.contactName = "";
  form.contactPhone = "";
  form.contactEmail = "";
  form.address = "";
  form.status = "0";
  form.remark = "";
};

// 初始化
onMounted(() => {
  console.log("获取供应商列表开始");
  console.log("查询参数初始值:", queryParams);

  // 检查当前用户权限
  if (localStorage.getItem("permissions")) {
    console.log("当前用户权限:", JSON.parse(localStorage.getItem("permissions") || "[]"));
  }

  getList();
});
</script>

<style lang="scss" scoped>
.supplier-container {
  .box-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .title {
        font-size: 18px;
        font-weight: bold;
      }

      .right-button {
        display: flex;
        gap: 10px;
      }
    }
  }

  .pagination {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }

  :deep(.el-upload-dragger) {
    width: 100%;
  }

  .empty-block {
    padding: 20px 0;
    text-align: center;

    .empty-tips {
      margin-top: 10px;
      color: #909399;
      font-size: 14px;
    }
  }
}
</style>
